package com.tempjob.app.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tempjob.common.exception.BusinessException;
import com.tempjob.common.model.ReGeo;
import com.tempjob.common.utils.HttpUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author hui
 * @Date 2023/12/22 17:53
 **/
@Slf4j
public class MapReverseGeocoding {

    public static void main(String[] args) {
        double latitude = 40.7128;  // 纬度
        double longitude = -74.0060;  // 经度
        String apiKey = "141d49a7950df086885505504aea7e68";  // 替换为你的高德地图API密钥

        try {
            // 构建请求URL
            String apiUrl = "https://restapi.amap.com/v5/geocode/regeo?key=" + apiKey + "&location=" + longitude + "," + latitude;
            // 创建HTTP连接
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 读取API响应
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 输出地点名称
            System.out.println("地点名称：" + extractLocationName(response.toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @SneakyThrows
    public static String getAddress(double latitude, double longitude) {
        String location = longitude + "," + latitude;
        String gaodeStreetApi = "https://restapi.amap.com/v3/geocode/regeo?key=141d49a7950df086885505504aea7e68&location=" + location;
        String reGeoResult = HttpUtils.sendGet(gaodeStreetApi, null,  null);
        log.info("经纬度分析地址:{},{},{}", location, reGeoResult);
        if (StringUtils.isNotEmpty(reGeoResult)) {
            ReGeo reGeo = JSON.parseObject(reGeoResult, ReGeo.class);
            if (reGeo.getStatus().equals(1)) {
                String formatAddress = reGeo.getRegeocode().getFormatted_address();
                return new String(formatAddress.getBytes("UTF-8"),"UTF-8");
            }
        }
        throw new BusinessException("地点解析失败");
    }

    private static String extractLocationName(String jsonResponse) {
        try {
            // 使用Gson库解析JSON响应
            JSONObject jsonObject = JSON.parseObject(jsonResponse);
            JSONObject regeocode = jsonObject.getObject("regeocode",JSONObject.class);
            if (regeocode != null) {
                String formattedAddress = regeocode.getString("formatted_address");
                return formattedAddress;
            } else {
                return "未找到地点名称";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "解析出错";
        }
    }


}
